package edu.towson.cosc.cosc455.kchung2.project1;

import java.util.HashSet;

import edu.towson.cosc.cosc455.interfaces.LexicalAnalyzer;

public class MyLexicalAnalyzer implements LexicalAnalyzer {
	HashSet<String> legalTokens;
	private String nextCharacter;
	private int currentPosition;
	private String sourceLine;
	private String newToken;
	/**
	 * initializing variables
	 */
	public MyLexicalAnalyzer(String line, HashSet<String> valid){
		sourceLine = line;
		legalTokens = valid;
		currentPosition = 0;
		nextCharacter = null;
		addCharacter();
	}
	/**
	 * if nextCharacter is '#', then collect the rest of the characters to get a valid markdown tag and set it as the current token
	 * otherwise, collect text and spaces and set as current token
	 */		
	@Override
	public void getNextToken() {
		// TODO Auto-generated method stub
		newToken = "";
		//skip \t ,\n, \r, " "
		while(isSkipable(nextCharacter)){
			getCharacter();
		}
		//if !# then read until #
		if(!isHashTag(nextCharacter)){
			while(!isHashTag(nextCharacter)){
				addCharacter();
			}
			Compiler.token = newToken;
		}
		//if #, read until space
		else{
			//add until space
			while(!isSpace(nextCharacter)){
				addCharacter();
			}
			//add the space
			addCharacter();
			//read again until space
			if(newToken.equalsIgnoreCase("#START ")||newToken.equalsIgnoreCase("#END ")){
				while(!isSkipable(nextCharacter) && !isHashTag(nextCharacter)){
					addCharacter();
				}
				lookupToken();
				Compiler.token = newToken;
			}
			else{
				lookupToken();
				Compiler.token = newToken;
			}
			
		}
	}
	/**
	 * Sets the next character of the source line
	 */
	@Override
	public void getCharacter() {
		// TODO Auto-generated method stub
		nextCharacter = Character.toString(sourceLine.charAt(currentPosition));
		currentPosition++;
	}
	/**
	 * Adds the next character and gets the next character of the source line
	 */
	public void addCharacter(){
		newToken += nextCharacter;
		getCharacter();
	}
	/**
	 * Checks to see if a character is a space.
	 */
	public boolean isSpace(String c) {
		// TODO Auto-generated method stub
		if (c.equals(" ")){
			return true;
		}
		return false;
	}
	public boolean isSkipable(String c) {
		// TODO Auto-generated method stub
		if (c.equals("\t") ||c.equals("\n") || c.equals("\r")|| c.equals(" ")){
			return true;
		}
		return false;
	}
	/**
	 * Checks to see if a character is a hash tag.
	 */
	public boolean isHashTag(String c) {
		// TODO Auto-generated method stub
		if (c.equals("#")){
			return true;
		}
		return false;
	}
	
	/**
	 * Checks to see if the newToken is a valid tag.
	 */
	@Override
	public void lookupToken(){
			// TODO Auto-generated method stub
	    if(!legalTokens.contains(newToken.toUpperCase())){
	    	System.out.println("Illegal Token found: " + newToken);
	    	System.exit(0);
	    }
	    
	}

}
